<?php

namespace doujunyu\utility;

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\TemplateProcessor;
use think\Exception;


/**
 * docx文件操作
 * Class SerCurl
 * @package App\Service
 */
class SelfDocx
{

    /**功能：编辑docx中的数据
     * @param string $url 文件路径
     * @param string $str_replace_string 更改的字符串
     * @param string $str_replace_image 图片名称
     * @param string $qrSize 二维码图大小
     * //对应参数请求格式
     * $str_replace_string = ['admin' => '管理员名称']
     * $str_replace_image = ['image' => ['src'=>'./uploads/20241211/58fec4b4b63d7a34660264e01844a370.jpg']];
     *
     */
    public static function edit_to_new_file(string $old_url,string $new_url,array $str_replace_string = [],array $str_replace_image = [])
    {
        if (!class_exists(TemplateProcessor::class)) {
            throw  new  Exception("请先执行 'composer require phpoffice/phpword'");
        }
        $a = new TemplateProcessor($old_url);
        foreach ($str_replace_string as $key => $val){
            $a->setValue($key,$val);
        }
        foreach ($str_replace_image as $key => $val){
            $a->setImageValue($key,$val);
        }
        $a->saveAs($new_url);
    }

    /** string数据转为word
     * @param string $save_url 保存路径
     * @param string $html html内容
     * @param int $auto_export 是否自动导出 0:否 1:是
     * @return bool|string
     */
    public static function textarea_to_word(string $save_url, string $html, int $auto_export = 0) {
        
        if (!class_exists(TemplateProcessor::class)) {
            throw new Exception("请先执行 'composer require phpoffice/phpword'");
        }
        $save_url = trim($save_url,'/');
        // 预处理 HTML，修复图片高度问题
        $html = preg_replace_callback('/<img([^>]*)style=[\'"]([^\'"]*)[\'"]([^>]*)>/i', function($matches) {
            $beforeStyle = $matches[1];
            $style = $matches[2];
            $afterStyle = $matches[3];
            
            // 从样式中提取宽度和高度
            preg_match('/width\s*:\s*(\d+)px/i', $style, $widthMatch);
            preg_match('/height\s*:\s*(\d+)px/i', $style, $heightMatch);
            
            $width = $widthMatch[1] ?? '';
            $height = $heightMatch[1] ?? '';
            
            // 如果找到宽度和高度，添加到 img 标签属性中
            if ($width && $height) {
                return "<img{$beforeStyle}width=\"{$width}\" height=\"{$height}\" style=\"{$style}\"{$afterStyle}>";
            }
            
            return $matches[0];
        }, $html);

        $phpWord = new PhpWord();
        $section = $phpWord->addSection();
        // 添加带格式的文本
        // $section->addText(
        //     '这是加粗的文本',
        //     ['bold' => true, 'size' => 16]
        // );
        \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html);

        $objWriter = IOFactory::createWriter($phpWord, 'Word2007');
        
        if ($auto_export == 1) {
            // 确保目录存在
            $dir = dirname('./'.$save_url);
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }
            $objWriter->save('./'.$save_url);
            return true;
        } else {
            ob_start();
            $objWriter->save('php://output');
            $file_content = ob_get_clean();
            return $file_content;
        }
    }

}